package com.beiyou.servlet;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;


/**
 * @author wzby
 * @Date:2022/8/24,17:58
 **/
@WebServlet(name = "javaServlet", value = "/java-servlet")
public class JavaServlet extends HttpServlet {
private List<User> userList;

    @Override
    public void init() throws ServletException {
        userList = new ArrayList<>();
        User user1 = new User();
        user1.setId(1);
        user1.setName("路西法");
        userList.add(user1);
        User user2 = new User();
        user2.setId(2);
        user2.setName("加百列");
        userList.add(user2);
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //getParameter（）根据参数名称获取参数值
        String idstr =  request.getParameter("id");

        String classStr = request.getParameter("classId");

        int id = Integer.parseInt(idstr==null?"0":idstr);
        //a？b:c 等效于
        //if(a)
        //return b;
        //else
        //return c;  a一般作为一个判断条件
        Optional<User> first = userList.stream().filter(u -> u.getId() == id).collect(Collectors.toList()).stream().findFirst();
        //Optional类  .isPresent（）如果值存在就执行使用该值的方法调用，否则什么也不做
        User user = new User();
        if(first.isPresent()){
            user=first.get();
        }
        //setAttribute设置属性
        request.setAttribute("user",user);
        request.setAttribute("userList",userList);

        request.setAttribute("name","化身恶魔");
        //.getRequestDispatcher获取调度  request请求
      request.getRequestDispatcher("java.jsp").forward(request,response);
      //request请求,response响应


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String id =req.getParameter("id");
        String name =req.getParameter("name");
        //resp.setHeader("Content-Type","text/html;charset=utf-8");代表输出时中文不会乱码
        //Content-Type的作用：该实体头的作用是让服务器告诉浏览器它发送的数据属于什么文件类型。
        resp.setHeader("Content-Type","text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("<html>");
        writer.println("<body>");
        writer.println("id:"+id);
        writer.println("<br/>");
        writer.println("name:"+name);
        writer.println("</body>");
        writer.println("</html>");
    }

    public void destroy() {
    }
}